<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :okText="isDetail ? '关闭' : '确定'"
    :footer="isDetail ? null : undefined"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 详情模式 -->
      <div v-if="isDetail">
        <!-- 打印内容区域 -->
        <div id="printContent" class="print-content">
          <div class="print-header">
            <h1>询单详情</h1>
            <div class="print-no">询单编号: {{ model.id || '-' }}</div>
          </div>

          <div class="print-info">
            <div class="print-info-item">
              <span class="label">客户名称:</span>
              <span class="value">{{ model.customerName || '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">客户电话:</span>
              <span class="value">{{ model.customerPhone || '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">门类型:</span>
              <span class="value">{{ model.type === 0 ? '推拉' : model.type === 1 ? '平开' : '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">物流信息:</span>
              <span class="value">{{ model.logisticsType === 0 ? '到付' : model.logisticsType === 1 ? '寄付' : '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">询单日期:</span>
              <span class="value">{{ model.inquiryDate ? model.inquiryDate.substr(0, 19).replace('T', ' ') : '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">状态:</span>
              <span class="value">{{ getStatusText(model.status) }}</span>
            </div>
            <div class="print-info-item full-width">
              <span class="label">收货地址:</span>
              <span class="value">{{ model.deliveryAddress || '-' }}</span>
            </div>
            <div class="print-info-item">
              <span class="label">总价:</span>
              <span class="value total-price">¥{{ model.totalPrice ? model.totalPrice.toFixed(2) : '0.00' }}</span>
            </div>
          </div>

          <div class="print-table">
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>规则名称</th>
                  <th>规则值</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in model.items" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.ruleName || '-' }}</td>
                  <td>{{ item.ruleValue || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="print-remark" v-if="model.remark">
            <div class="label">备注:</div>
            <div class="value">{{ model.remark }}</div>
          </div>

          <div class="print-footer">
            <div class="print-sign">
              <div class="sign-item">
                <div class="label">客户签名:</div>
                <div class="line"></div>
              </div>
              <div class="sign-item">
                <div class="label">业务员:</div>
                <div class="line"></div>
              </div>
              <div class="sign-item">
                <div class="label">审核人:</div>
                <div class="line"></div>
              </div>
            </div>
            <div class="print-date">打印日期: {{ printDate }}</div>
          </div>
        </div>

        <!-- 打印和导出按钮 -->
        <div class="print-actions">
          <a-button type="primary" @click="handlePrint">
            <a-icon type="printer" />打印询单
          </a-button>
          <a-button @click="handleExportPDF" style="margin-left: 8px;">
            <a-icon type="file-pdf" />导出PDF
          </a-button>
        </div>
      </div>

      <!-- 编辑模式 -->
      <a-form-model
        v-else
        ref="form"
        :model="model"
        :rules="validatorRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <!-- 门类型选择 -->
        <a-form-model-item label="门类型" prop="doorType">
          <a-radio-group v-model="model.doorType" @change="handleDoorTypeChange">
            <a-radio :value="0">推拉</a-radio>
            <a-radio :value="1">平开</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <!-- 动态规则表单 -->
        <div v-if="inquiryRules.length > 0">
          <a-divider>询单规则</a-divider>
          <a-form-model-item
            v-for="rule in inquiryRules"
            :key="rule.id"
            :label="rule.name"
            :prop="`ruleValues.${rule.id}`"
            :rules="rule.isMust === 1 ? [{ required: true, message: `请选择${rule.name}` }] : []"
          >
            <a-select
              v-model="model.ruleValues[rule.id]"
              placeholder="请选择"
              allowClear
            >
              <a-select-option
                v-for="(value, index) in rule.values"
                :key="`${rule.id}-${index}`"
                :value="value.value"
              >
                {{ value.value }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

export default {
  name: 'InquiryDetailModal',
  data() {
    return {
      title: '操作',
      visible: false,
      isDetail: false,
      model: {
        doorType: 0,
        ruleValues: {},
        items: []
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      confirmLoading: false,
      validatorRules: {
        doorType: [{ required: true, message: '请选择门类型!' }]
      },
      inquiryRules: [],
      printDate: new Date().toLocaleString(),
      detailColumns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '规则名称',
          dataIndex: 'ruleName',
          width: 120,
          align: 'center'
        },
        {
          title: '规则值',
          dataIndex: 'ruleValue',
          width: 200,
          align: 'center'
        }
      ]
    }
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.isDetail = false
      this.model = Object.assign({}, record)
      this.model.doorType = this.model.doorType || 0
      this.model.ruleValues = {}
      this.visible = true
      this.title = record.id ? '编辑' : '新增'
      // 加载询单规则
      this.loadInquiryRules()
    },
    detail(record) {
      this.isDetail = true
      this.visible = true
      this.title = '询单详情'
      this.confirmLoading = true
      
      // 调用新的详情API获取完整数据
      httpAction('/oms/inquiry/queryById?id=' + record.id, {}, 'get').then((res) => {
        if (res.success) {
          this.model = Object.assign({}, res.result)
        } else {
          this.$message.error('获取详情失败：' + res.message)
        }
      }).catch((error) => {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.isDetail = false
      this.model = {
        doorType: 0,
        ruleValues: {},
        items: []
      }
      this.inquiryRules = []
    },
    getStatusColor(status) {
      const colorMap = {
        0: 'orange',
        1: 'blue', 
        2: 'green'
      }
      return colorMap[status] || 'default'
    },
    getStatusText(status) {
      const textMap = {
        0: '待处理',
        1: '已处理',
        2: '已完成'
      }
      return textMap[status] || '-'
    },
    handleOk() {
      if (this.isDetail) {
        this.handleCancel()
        return
      }
      
      const that = this
      // 执行表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl = '/oms/inquiry/add'
            method = 'post'
          } else {
            httpurl = '/oms/inquiry/edit'
            method = 'put'
          }

          // 构建提交数据
          const submitData = {
            ...this.model,
            items: this.buildInquiryItems()
          }

          httpAction(httpurl, submitData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.handleCancel()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleDoorTypeChange() {
      // 门类型改变时重新加载规则
      this.model.ruleValues = {}
      this.loadInquiryRules()
    },
    loadInquiryRules() {
      const that = this
      that.confirmLoading = true

      // 加载询单规则
      httpAction('/oms/inquiry/rule/listByType?type=' + this.model.doorType, {}, 'get').then((res) => {
        if (res.success) {
          that.inquiryRules = res.result || []

          // 为每个规则加载规则值
          const promises = that.inquiryRules.map(rule => {
            return httpAction('/oms/omsInquiryRuleValue/listByRuleId?ruleId=' + rule.id, {}, 'get').then((valueRes) => {
              if (valueRes.success) {
                rule.values = valueRes.result || []
              }
            })
          })

          Promise.all(promises).then(() => {
            // 如果是编辑模式，加载已有的询单项数据
            if (that.inquiryId) {
              that.loadInquiryItems()
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        } else {
          that.$message.warning(res.message)
          that.confirmLoading = false
        }
      }).catch(() => {
        that.confirmLoading = false
      })
    },
    loadInquiryItems() {
      const that = this

      httpAction('/oms/omsInquiryItem/listByInquiryId?inquiryId=' + this.inquiryId, {}, 'get').then((res) => {
        if (res.success) {
          const items = res.result || []
          const ruleValues = {}

          items.forEach(item => {
            ruleValues[item.ruleId] = item.ruleValue
          })

          that.model.ruleValues = ruleValues
        }
      })
    },
    // 打印询单
    handlePrint() {
      // 创建新窗口进行打印，避免影响当前页面
      const printWindow = window.open('', '_blank', 'width=800,height=600')
      const printContent = document.getElementById('printContent').innerHTML

      printWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <title>询单详情打印</title>
            <style>
              body { margin: 0; padding: 20px; font-family: SimSun, sans-serif; }
              .print-content { width: 100%; max-width: 800px; margin: 0 auto; }
              .print-header { text-align: center; margin-bottom: 20px; }
              .print-header h1 { font-size: 24px; margin: 0; }
              .print-no { font-size: 14px; margin-top: 10px; }
              .print-info { display: flex; flex-wrap: wrap; margin-bottom: 20px; }
              .print-info-item { width: 50%; margin-bottom: 10px; display: flex; }
              .print-info-item.full-width { width: 100%; }
              .label { font-weight: bold; margin-right: 10px; min-width: 80px; }
              .total-price { color: #f5222d; font-weight: bold; font-size: 16px; }
              .print-table { margin-bottom: 20px; }
              table { width: 100%; border-collapse: collapse; }
              th, td { border: 1px solid #000; padding: 8px; text-align: center; font-size: 12px; }
              th { background-color: #f0f0f0; }
              .print-remark { margin-bottom: 20px; }
              .print-footer { margin-top: 40px; }
              .print-sign { display: flex; justify-content: space-between; margin-bottom: 40px; }
              .sign-item { width: 30%; }
              .line { border-bottom: 1px solid #000; height: 30px; }
              .print-date { text-align: right; font-size: 12px; }
              @media print {
                @page { margin: 0.5in; }
                body { margin: 0; }
              }
            </style>
          </head>
          <body>
            ${printContent}
          </body>
          </html>
        `)

      printWindow.document.close()

      // 等待内容加载完成后打印
      printWindow.onload = function () {
        printWindow.print()
        printWindow.close()
      }
    },
    // 导出PDF
    handleExportPDF() {
      this.confirmLoading = true
      
      // 显示加载提示
      this.$message.loading('正在生成PDF，请稍候...', 0)
      
      // 获取原始元素
      const originalElement = document.getElementById('printContent')
      
      // 创建一个临时容器，用于存放处理后的内容
      const tempContainer = document.createElement('div')
      tempContainer.innerHTML = originalElement.innerHTML
      tempContainer.style.width = originalElement.offsetWidth + 'px'
      tempContainer.style.padding = '20px'
      tempContainer.style.background = '#fff'
      tempContainer.style.position = 'absolute'
      tempContainer.style.left = '-9999px'
      tempContainer.style.top = '-9999px'
      
      // 将临时容器添加到文档中
      document.body.appendChild(tempContainer)
      
      // 使用setTimeout确保DOM已完全渲染
      setTimeout(() => {
        html2canvas(tempContainer, {
          scale: 2,
          useCORS: true,
          logging: false,
          allowTaint: true,
          backgroundColor: '#ffffff'
        }).then(canvas => {
          // 移除临时容器
          document.body.removeChild(tempContainer)
          
          const imgData = canvas.toDataURL('image/png')
          const pdf = new jsPDF({
            orientation: 'portrait',
            unit: 'mm',
            format: 'a4'
          })
          const imgWidth = 210 // A4纵向宽度
          const pageHeight = 297 // A4纵向高度
          const imgHeight = canvas.height * imgWidth / canvas.width
          let heightLeft = imgHeight
          let position = 0
          
          pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
          heightLeft -= pageHeight
          
          while (heightLeft > 0) {
            position = heightLeft - imgHeight
            pdf.addPage()
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
            heightLeft -= pageHeight
          }
          
          pdf.save(`询单详情-${this.model.customerName || '未命名'}.pdf`)
          this.confirmLoading = false
          // 关闭加载提示
          this.$message.destroy()
          this.$message.success('PDF导出成功')
        }).catch(error => {
          // 移除临时容器
          if (document.body.contains(tempContainer)) {
            document.body.removeChild(tempContainer)
          }
          console.error('导出PDF失败', error)
          this.$message.error(`导出PDF失败: ${error.message || '未知错误'}`)
          this.confirmLoading = false
          // 关闭加载提示
          this.$message.destroy()
        })
      }, 1000) // 延长延迟时间，确保DOM渲染完成
    }
  }
}
</script>

<style scoped>
.print-content {
  padding: 20px;
  background-color: #fff;
}
.print-header {
  text-align: center;
  margin-bottom: 20px;
}
.print-header h1 {
  font-size: 24px;
  margin: 0;
}
.print-no {
  font-size: 14px;
  margin-top: 10px;
}
.print-info {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}
.print-info-item {
  width: 50%;
  margin-bottom: 10px;
  display: flex;
}
.print-info-item.full-width {
  width: 100%;
}
.label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}
.total-price {
  color: #f5222d;
  font-weight: bold;
  font-size: 16px;
}
.print-table {
  margin-bottom: 20px;
}
table {
  width: 100%;
  border-collapse: collapse;
}
th,
td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
}
th {
  background-color: #f0f0f0;
}
.print-remark {
  margin-bottom: 20px;
}
.print-footer {
  margin-top: 40px;
}
.print-sign {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
}
.sign-item {
  width: 30%;
}
.line {
  border-bottom: 1px solid #000;
  height: 30px;
}
.print-date {
  text-align: right;
  font-size: 12px;
}
.print-actions {
  text-align: center;
  margin-top: 20px;
}
</style>
